package seentao.stdev.mobile.webuser.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import lombok.extern.log4j.Log4j;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import seentao.stdev.mobile.base.model.DataModel;
import seentao.stdev.mobile.base.model.ErrorModel;
import seentao.stdev.mobile.base.model.Model;
import seentao.stdev.mobile.base.model.SuccessModel;
import seentao.stdev.mobile.webuser.service.WebUserService;
import seentao.stdev.mobile.webuser.vo.WebUser;

@Log4j
@RestController
@RequestMapping("/serv/users")
public class LoginController {
	
	@Resource
	private WebUserService service;
	
	@Resource
	private HttpSession session;

	@RequestMapping("login")
	public Model login(WebUser user) {
		logout();
		WebUser findUser = service.find(user);
		if (findUser != null) {
			session.setAttribute("WEB_USER", findUser);
			return new SuccessModel();
		} else {
			log.info("认证失败, 错误的用户名或密码");
			return new ErrorModel("认证失败, 错误的用户名或密码");
		}
	}
	
	@RequestMapping("isLogin")
	public Model isLogin() {
		Map<String, Object> data = new HashMap<>();
		data.put("isLogin", isInSession());
		if (isInSession()) {
			log.debug(getSessionUser());
			data.put("usertype", new String[]{"manager","student","teacher"}[getSessionUser().getUsertype()]);
		}
		return new DataModel(data);
	}
	
	@RequestMapping("logout")
	public Model logout() {
		session.invalidate();
		return new SuccessModel();
	}
	
	private boolean isInSession() {
		return session.getAttribute("WEB_USER") != null;
	}
	
	private WebUser getSessionUser() {
		return (WebUser) session.getAttribute("WEB_USER");
	}
	

}
